import pysvn
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "capstone.settings")
from django.core.management import setup_environ
from capstone import settings
setup_environ(settings)
from agile.models import Repository, Revision
from datetime import datetime
import time

class SvnUpdater():
    def __init__(self, repo):
        self.repo = repo
        
    def update(self):
        client = pysvn.Client()
        client.commit_info_style = 1
        client.callback_get_login = self.get_login
        r_num = 1
        rev_list = Revision.objects.filter(repo = self.repo.pk).order_by('number')
        if rev_list != None and rev_list.count() > 0:
            r_num = rev_list[0].number + 1
        rstart = pysvn.Revision(pysvn.opt_revision_kind.number, r_num)
        rend = pysvn.Revision(pysvn.opt_revision_kind.date, time.mktime(datetime.now().timetuple()))
        log = client.log(self.repo.url, revision_start=rstart, revision_end=rend)
        for info in log:
            self.save_rev(info)
    
    def get_login(self, realm, user_name, may_save):
        return True, self.repo.username, self.repo.password, True
    
    def save_rev(self, revinfo):
        if Revision.objects.filter(repo=self.repo.pk, number=revinfo['revision'].number).count() != 0:
            return
        rev = Revision()
        rev.repo = self.repo
        rev.number = revinfo['revision'].number
        if 'author' in revinfo:
            rev.author = revinfo['author']
        else:
            rev.author = '---'
        rev.timestamp = datetime.fromtimestamp(revinfo['date'])
        rev.message = revinfo['message']
        rev.save()
    
if __name__ == '__main__':
    repos = Repository.objects.all()
    for repo in repos:
        updater = SvnUpdater(repo)
        updater.update()